# -*- coding:utf-8 -*-
# @Time : 2021/2/26 14:23
# @Author : Administrator
# @File : haokan.py
# @Software: PyCharm
# @Motto: good good study,day day up

from loguru import logger
import requests
from pathlib import Path
import os


headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}


def get_response(url):
    response = requests.get(url=url, headers=headers).json()
    videos = response['data']['response']['videos']
    return videos


def save(title, video_content):
    video_path = Path.cwd().parent / 'video'
    if not os.path.exists(video_path):
        os.mkdir(video_path)
    video_name = video_path.joinpath(f'{title}.mp4')
    with open(video_name, 'wb') as f:
        f.write(video_content)
        logger.info(f'正在保存：{title}')


def videos(url):
    response = get_response(url)
    for item in response:
        title = item['title']
        video_url = item['poster_small']
        video_content = requests.get(url=video_url, headers=headers).content
        save(title, video_content)


if __name__ == '__main__':
    videos('https://haokan.baidu.com/web/video/feed?tab=gaoxiao_new&act=pcFeed&pd=pc&num=60&shuaxin_id=1614313677380')
